/**
 * 3η ΓΕ 2013-2014 - Super Market
 * ΦΡΑΓΚΟΥΛΟΠΟΥΛΟΥ ΕΜΜΑΝΟΥΕΛΑ (69298)
 * ΧΑΛΔΑΣ ΧΑΡΑΛΑΜΠΟΣ (69305)
 * ΧΟΡΜΟΒΙΤΗΣ ΙΩΑΝΝΗΣ (69325)
 * ΧΟΥΣΤΟΥΛΑΚΗ ΕΥΑΓΓΕΛΙΑ (69327)
 */
package administratorGUI;

import supermarket.ProductItem;
import supermarket.StoreItem;
import java.awt.event.ItemEvent;
import java.util.List;
import javax.persistence.TypedQuery;
import javax.swing.*;
import static javax.swing.JOptionPane.YES_NO_OPTION;
import static javax.swing.JOptionPane.YES_OPTION;
import model.*;
import supermarket.EntityManagerFactory;

/**
 * Οθόνη Συσχετισμού Καταστημάτων - Προϊόντων
 */
public class ProductsPerStoreForm extends javax.swing.JInternalFrame {

    /**
     * Constructor
     */
    public ProductsPerStoreForm() {
        initComponents();
        prepareStoresCombo();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        SuperMarketPUEntityManager = java.beans.Beans.isDesignTime() ? null : EntityManagerFactory.getEntityManager();
        jPanel4 = new javax.swing.JPanel();
        selectProduct = new javax.swing.JButton();
        unSelectProduct = new javax.swing.JButton();
        jScrollPane5 = new javax.swing.JScrollPane();
        selectedProducts = new javax.swing.JList(new DefaultListModel());
        selectedProductsLabel = new javax.swing.JLabel();
        saveStoreProduct = new javax.swing.JButton();
        restoreButton = new javax.swing.JButton();
        storeCombo = new javax.swing.JComboBox();
        jScrollPane4 = new javax.swing.JScrollPane();
        availiableProducts = new javax.swing.JList(new DefaultListModel());
        availableProductsLabel = new javax.swing.JLabel();
        storeLabel = new javax.swing.JLabel();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setTitle("Συσχέτιση προϊόντων και καταστημάτων");

        selectProduct.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/icons/right.png"))); // NOI18N
        selectProduct.setToolTipText("Επιλογή");
        selectProduct.setBorder(null);
        selectProduct.setBorderPainted(false);
        selectProduct.setPreferredSize(new java.awt.Dimension(24, 24));
        selectProduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectProductActionPerformed(evt);
            }
        });

        unSelectProduct.setBackground(new java.awt.Color(255, 255, 255));
        unSelectProduct.setForeground(new java.awt.Color(255, 255, 255));
        unSelectProduct.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/icons/left.png"))); // NOI18N
        unSelectProduct.setToolTipText("Αποερπιλογή");
        unSelectProduct.setBorder(null);
        unSelectProduct.setBorderPainted(false);
        unSelectProduct.setPreferredSize(new java.awt.Dimension(24, 24));
        unSelectProduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                unSelectProductActionPerformed(evt);
            }
        });

        jScrollPane5.setViewportView(selectedProducts);

        selectedProductsLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        selectedProductsLabel.setText("Επιλεγμένα προϊόντα");

        saveStoreProduct.setText("Αποθήκευση");
        saveStoreProduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveStoreProductActionPerformed(evt);
            }
        });

        restoreButton.setText("Επαναφορά");
        restoreButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                restoreButtonActionPerformed(evt);
            }
        });

        storeCombo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                storeListStateChanged(evt);
            }
        });

        jScrollPane4.setViewportView(availiableProducts);

        availableProductsLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        availableProductsLabel.setText("Διαθέσιμα προϊόντα");

        storeLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        storeLabel.setText("Κατάστημα");

        org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, storeLabel)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, storeCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 255, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel4Layout.createSequentialGroup()
                        .add(1, 1, 1)
                        .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jPanel4Layout.createSequentialGroup()
                                .add(jScrollPane4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 255, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(18, 18, 18)
                                .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(unSelectProduct, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(selectProduct, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                            .add(availableProductsLabel))
                        .add(18, 18, 18)
                        .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(selectedProductsLabel)
                            .add(jScrollPane5))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(saveStoreProduct, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 123, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(restoreButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 123, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );

        jPanel4Layout.linkSize(new java.awt.Component[] {selectProduct, unSelectProduct}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .add(storeLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(5, 5, 5)
                .add(storeCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(availableProductsLabel)
                    .add(selectedProductsLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel4Layout.createSequentialGroup()
                        .add(saveStoreProduct)
                        .add(18, 18, 18)
                        .add(restoreButton))
                    .add(jPanel4Layout.createSequentialGroup()
                        .add(selectProduct, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(37, 37, 37)
                        .add(unSelectProduct, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                        .add(jScrollPane5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                        .add(jScrollPane4)))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents


    /**
     * Button: Επιλογή Προϊόντων
     * @param evt 
     */
     private void selectProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectProductActionPerformed

         DefaultListModel lsm1 = (DefaultListModel) availiableProducts.getModel();
         DefaultListModel lsm2 = (DefaultListModel) selectedProducts.getModel();

         int len = availiableProducts.getSelectedIndices().length;

         if (len > 0) {
             for (int i = len - 1; i >= 0; i--) {
                 int idx = availiableProducts.getSelectedIndices()[i];
                 lsm2.addElement(lsm1.getElementAt(idx));
                 lsm1.remove(idx);
             }
         }
     }//GEN-LAST:event_selectProductActionPerformed

     /**
      * Button: Αποεπιλογή Προϊόντων
      * @param evt 
      */
     private void unSelectProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_unSelectProductActionPerformed

         DefaultListModel lsm1 = (DefaultListModel) availiableProducts.getModel();
         DefaultListModel lsm2 = (DefaultListModel) selectedProducts.getModel();

         int len = selectedProducts.getSelectedIndices().length;

         if (len > 0) {
             for (int i = len - 1; i >= 0; i--) {
                 int idx = selectedProducts.getSelectedIndices()[i];
                 lsm1.addElement(lsm2.getElementAt(idx));
                 lsm2.remove(idx);
             }
         }
     }//GEN-LAST:event_unSelectProductActionPerformed

     /**
      * Button: Επαναφορά
      * @param evt 
      */
     private void restoreButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_restoreButtonActionPerformed
         fillProductStoreLists((StoreItem) storeCombo.getSelectedItem());
     }//GEN-LAST:event_restoreButtonActionPerformed

     /**
      * Όταν αλλάζει το επιλεγμένο Κατάστημα, γεμίζει τις Λίστες
      * με τα Διαθέσιμα και Επιλεγμένα Προϊόντα
      * @param evt 
      */
     private void storeListStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_storeListStateChanged
         if (evt.getStateChange() == ItemEvent.SELECTED) {
             fillProductStoreLists((StoreItem) storeCombo.getSelectedItem());
         }
     }//GEN-LAST:event_storeListStateChanged

     /**
      * Button: Αποθήκευση
      * @param storeItem 
      */
     private void saveStoreProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveStoreProductActionPerformed
  
        if (JOptionPane.showConfirmDialog(this,
                 "Να αποθηκευτούν οι αλλαγές;",
                 "Αποθήκευση", YES_NO_OPTION) == YES_OPTION) {
             saveProductStoreLists((StoreItem) storeCombo.getSelectedItem());
         }
     }//GEN-LAST:event_saveStoreProductActionPerformed


     /**
      * Αποθήκευση
      * @param storeItem 
      */
    public void saveProductStoreLists(StoreItem storeItem) {
        DefaultListModel lsm1 = (DefaultListModel) availiableProducts.getModel();
        DefaultListModel lsm2 = (DefaultListModel) selectedProducts.getModel();
        SuperMarketPUEntityManager.getTransaction().begin();

        // Αφαιρώ τα μη επιλεγμένα 
        for (int i = 0; i < lsm1.size(); ++i) {
            ProductItem item = (ProductItem) lsm1.get(i);
            Product p = item.getProduct();
            List<Store> storeList = (List<Store>) p.getStoreList();
            for (int j = 0; j < storeList.size(); ++j) {
                if (storeList.get(j).getStoreId() == storeItem.getStore().getStoreId()) {
                    storeList.remove(j);
                    break;
                }
            }
            SuperMarketPUEntityManager.persist(p);
        }
        
        // Προσθέτω τα επιλεγμένα
        for (int i = 0; i < lsm2.size(); ++i) {
            ProductItem item = (ProductItem) lsm2.get(i);
            Product p = item.getProduct();
            List<Store> storeList = (List<Store>) p.getStoreList();
            boolean found = false;
            for (int j = 0; j < storeList.size(); ++j) {
                if (storeList.get(j).getStoreId() == storeItem.getStore().getStoreId()) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                storeList.add(storeItem.getStore());
            }
            SuperMarketPUEntityManager.persist(p);
        }
        SuperMarketPUEntityManager.getTransaction().commit();
    }

    /**
     * 
     * @param storeItem 
     */
    public void fillProductStoreLists(StoreItem storeItem) {
        // Καθαρίζω τις Λίστες
        DefaultListModel lsm1 = (DefaultListModel) availiableProducts.getModel();
        lsm1.removeAllElements();
        DefaultListModel lsm2 = (DefaultListModel) selectedProducts.getModel();
        lsm2.removeAllElements();

        // Διαβάζω τα προϊόντα από το Table [PRODUCT]
        TypedQuery<Product> q = SuperMarketPUEntityManager
                .createNamedQuery("Product.findAll", Product.class);
        List<Product> ls = q.getResultList();
        
        // Σαρώνω τη Λίστα με τα Προϊόντα
        for (int i = 0; i < ls.size(); ++i) {
            List<Store> belongsTo = (List<Store>) ls.get(i).getStoreList();
            boolean found = false;
            for (int j = 0; j < belongsTo.size(); ++j) {
                if (belongsTo.get(j).getStoreId() == storeItem.getStore().getStoreId()) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                lsm1.addElement(new ProductItem(ls.get(i)));
            } else {
                lsm2.addElement(new ProductItem(ls.get(i)));
            }
        }
    }

    /**
     * Γεμίζει το Combo με τα Καταστήματα
     */
    public void prepareStoresCombo() {
        // Καθαρισμός Combo
        storeCombo.removeAllItems();
        
        // Διαβάζω τα Καταστήματα από το Table [STORE]
        TypedQuery<Store> query = SuperMarketPUEntityManager
                .createNamedQuery("Store.findAll", Store.class);
        if (query.getResultList().isEmpty()) {
            return;
        }
        
        // Γεμίζω το Combo
        List<Store> ls = query.getResultList();
        for (int i = 0; i < ls.size(); ++i) {
            storeCombo.addItem(new StoreItem(ls.get(i)));
        }
        
        // Γεμίζω τις Λίστες Διαθέσιμων και Επιλεγμένων Προϊόντων
        fillProductStoreLists((StoreItem) storeCombo.getSelectedItem());
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager SuperMarketPUEntityManager;
    private javax.swing.JLabel availableProductsLabel;
    private javax.swing.JList availiableProducts;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JButton restoreButton;
    private javax.swing.JButton saveStoreProduct;
    private javax.swing.JButton selectProduct;
    private javax.swing.JList selectedProducts;
    private javax.swing.JLabel selectedProductsLabel;
    private javax.swing.JComboBox storeCombo;
    private javax.swing.JLabel storeLabel;
    private javax.swing.JButton unSelectProduct;
    // End of variables declaration//GEN-END:variables
}
